package com.example.translateappjava.Fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.translateappjava.Activity.KnowledgeFragmentActivity.NewsDetailsActivity;
import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.Adapter.NewsInfo;
import com.example.translateappjava.Adapter.NewsListAdapter;
import com.example.translateappjava.R;
import com.example.translateappjava.Utils.DataItem;
import com.example.translateappjava.Utils.DataItemAdaptor;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.xml.parsers.SAXParser;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class KnowledgeFragment extends Fragment {

    private ListView listView;
    private DataItemAdaptor dataItemAdaptor;
    private List<DataItem> dataList;
    private ArrayList<String> key =new ArrayList<String>(){{
       add("a68b93a83f4b447420aba45856ef51c2");
       add("8c8cd4a31dbfc3069e98161ea0e81127");
       add("fa86611acc58cbfa0d6f3b90e53ddc4d");
       add("87d33f62d85da75441321b5942668456");
       add("7761a3f5723f400ea36bec8d73ec040b");
       add("f52ecee407e86ec98b1e8cd2a9f9f8e3");
       add("a2c5215823ed81d7ef7079f3d08343f8");
    }};


    private int index=0;

    private String url="http://v.juhe.cn/toutiao/index?key="+key.get(index)+"&type=jiankang";

    private RecyclerView recyclerView;

    private NewsListAdapter mNewsListAdapter;

    private Handler mHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==100){
                String data = (String) msg.obj;
                NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
                if (newsInfo!=null && newsInfo.getError_code()==0){
                    if(null!=mNewsListAdapter){
                        mNewsListAdapter.setListData(newsInfo.getResult().getData());
                    }

                }else{
                    if (index<2) {
                        index++;
                    }
                    if (index > 6)
                    {
                        index= 0;
                    }
                    updateListView(0);
                    Toast.makeText(getActivity(), "请稍等", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_knowledge, container, false);

        TabLayout tabLayout = view.findViewById(R.id.TabLayout);
//        listView = view.findViewById(R.id.ListView_1);
        recyclerView = view.findViewById(R.id.recyclerView);

        ThemeUtilsActivity.applyTheme(view);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateListView(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        // 自动选择第一个 Tab（Tab 1）
        if (tabLayout.getTabCount() > 0) {
            TabLayout.Tab tab = tabLayout.getTabAt(0);
            if (tab != null) {
                tab.select();
                updateListView(0);  // 手动调用更新方法
            }
        }


        return view;
    }

    private void updateListView(int position) {
        dataList = new ArrayList<>();
        switch (position) {
            case 0:
                System.out.println("1");
                url="http://v.juhe.cn/toutiao/index?key="+key.get(index)+"&type=jiankang";
                getHttpData();
                break;
            case 1:
                System.out.println("2");
                url="http://v.juhe.cn/toutiao/index?key="+key.get(index)+"&type=top";
                getHttpData();
                break;
            case 2:
                System.out.println("3");
                url="http://v.juhe.cn/toutiao/index?key="+key.get(index)+"&type=guonei";
                getHttpData();
            case 3:
                System.out.println("4");
                url="http://v.juhe.cn/toutiao/index?key="+key.get(index)+"&type=guoji";
                getHttpData();
                break;
        }



//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                DataItem selectedItem = dataList.get(position);
//                Toast.makeText(getActivity(), "Clicked: " + selectedItem.getContext(), Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mNewsListAdapter = new NewsListAdapter(getActivity());
        recyclerView.setAdapter(mNewsListAdapter);
        //click
        mNewsListAdapter.setMonItemClickListener(new NewsListAdapter.onItemClickListener() {
            @Override
            public void onItemClick(NewsInfo.ResultBean.DataBean dataBean, int positon) {
                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                intent.putExtra("dataBean",dataBean);
                startActivity(intent);
            }
        });
        //获取数据

    }
    private void getHttpData(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("--------------","onFailure"+e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String data = response.body().string();
//                Log.d("---------","onResponse: "+data);
                Message message = new Message();
                //指定一个标识符
                message.what = 100;
                message.obj = data;
                mHandler.sendMessage(message);


            }
        });
    }
    @Override
    public void onResume() {
        super.onResume();
        View rootView = getView();
        if (rootView != null) {
            ThemeUtilsActivity.applyTheme(rootView);
        }
    }


}